package com.gombe.credit.app.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.ActGombeCreditUserFeedbackPageBinding
import com.gombe.credit.app.databinding.ActGombeCreditUserFeedbackQuestionTypeItemBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.HttpHelper
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditUserFeedbackImage
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.imgcovert.ImageConvert
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.weight.font.LexendMediumEditText
import com.gombe.credit.lib.adapter.GombeCreditOnItemChildClickListener
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import java.io.File

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 13:45
 * @Annotation：意见反馈
 */
class ActGombeCreditUserFeedback: CommonActivity() {
    lateinit var binding: ActGombeCreditUserFeedbackPageBinding
    private val typeTitleList = arrayListOf(R.string.gombe_credit_feedback_type_1,R.string.gombe_credit_feedback_type_2,R.string.gombe_credit_feedback_type_3,R.string.gombe_credit_feedback_type_4,R.string.gombe_credit_feedback_type_5,R.string.gombe_credit_feedback_type_6)
    private val typeValueList = arrayListOf("HARASSMENT","PAYOUT ISSUE","SCAM","DECLINED","DATA MISUSE","OTHERS")
    //反馈类型列表
    private var typeList = arrayListOf<JSONObject>()

    //图片列表
    private var pictureAdapter: AdapterGombeCreditUserFeedbackImage? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_COUNT = "starCount"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, ActGombeCreditUserFeedback::class.java)
            intent.putExtra(INTENT_KEY_STAR_COUNT, count)
            context.startActivity(intent)
        }
    }

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditUserFeedbackPageBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initGombeCreditView() {
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditTextTitle(getString(R.string.gombe_credit_feedback_title))
        setGombeCreditTextTitleColor(getColor(R.color.black))
        setGombeCreditRightBtnRes(R.mipmap.gombe_credit_image_customer_black_icon)
        setGombeCreditBackBtnRes(R.mipmap.gombe_credit_image_back_black_icon)
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)

        initFeedbackRecyclerView()
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                GombeCreditLogger.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    GombeCreditLogger.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        pictureAdapter?.let {
                            //最多只能选三张
                            if (it.itemCount == 3){
                                it.removeItem(0)
                            }
                            val imgObj = JSONObject()
                            imgObj.put("isDefault",false)
                            imgObj.put("imgPath",localPath)
                            it.addLastItem(imgObj)

                            uploadGombeCreditImageFileAction(localPath)
                        }
                    }
                }

            } else {
                GombeCreditLogger.e("No media selected")
            }
        }
    }

    override fun initGombeCreditListener() {
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Feedback Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"Feedback Page")
            }
        })
        //输入框监听
        binding.userAdviseRemark.addTextChangedListener(IRemarkChangeListener)
        binding.userAdviseRemark.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.USER_FEEDBACK_REMARK,remark)
            }
        })
        //联系邮箱地址
        binding.feedbackEmail.setInputFocusChangeListener(object : LexendMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_FORM.USER_FEEDBACK_EMAIL,remark)
            }
        })

        //提交
        binding.btnSubmit.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                //问题类型
                if (getSelectTypeItem() == null){
                    showGombeCreditToast(getString(R.string.gombe_credit_feedback_question_type))
                    return
                }
                val remark = binding.userAdviseRemark.text.toString()
                if (remark.isEmpty()){
                    showGombeCreditToast(getString(R.string.gombe_credit_feedback_remark_title))
                    return
                }
                val email = binding.feedbackEmail.text.toString()
                if (email.isEmpty()){
                    showGombeCreditToast(getString(R.string.gombe_credit_feedback_email_hint))
                    return
                }
                showGombeCreditLoading(isTOuchOut = false, isCancel = true)
                val params = JSONObject().addCommonParams().apply {
                    put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_FEEDBACK_SUBMIT_PATH)
                    put("opinion",remark)//反馈内容
                    put("email",email)//邮箱
                }
                getSelectTypeItem()?.let {
                    params.put("type",it.optString("value"))//反馈类型
                }
                val imgUrls = getSelectImageUrls()
                if (imgUrls.isNotEmpty()){
                    params.put("images",imgUrls)
                }
                val starCount = getStarCount()
                if (starCount.isNotEmpty()){
                    params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
                }

                submitFeedbackAction(params)
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_FEEDBACK_SUBMIT)
            }
        })
    }

    override fun takeGombeCreditData() {
        loadFeedbackQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        pictureAdapter?.addFirstItem(imgObj)
    }

    /**
     * 初始化图片列表
     */
    private fun initFeedbackRecyclerView() {
        binding.userAdviseGridView.setHasFixedSize(false)
        binding.userAdviseGridView.isNestedScrollingEnabled = false
        binding.userAdviseGridView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.userAdviseGridView.layoutManager = layoutManager
        pictureAdapter = AdapterGombeCreditUserFeedbackImage(binding.userAdviseGridView)
        binding.userAdviseGridView.adapter = pictureAdapter
        binding.userAdviseGridView.itemAnimator = DefaultItemAnimator()
        pictureAdapter?.setOnItemChildClickListener(GombeCreditOnItemChildClickListener { parent, childView, position ->
            pictureAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.pictureRemove -> {//删除
                        if (!item.optBoolean("isDefault")) {
                            it.removeItem(position)

                            //是否需要添加默认图片
                            var isAddDefault = true
                            for (i in 0..<it.itemCount) {
                                if (it.getItem(i).optBoolean("isDefault")) {
                                    isAddDefault = false
                                    break
                                }
                            }
                            if (isAddDefault) {
                                val imgObj = JSONObject()
                                imgObj.put("isDefault", true)
                                it.addFirstItem(imgObj)
                            }
                        }
                    }

                    R.id.imageAdd -> {//选择图片
                        if (item.optBoolean("isDefault")) {
                            hasRequestPermissions()
                        }
                    }
                }
            }
        })
    }

    private val IRemarkChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        @SuppressLint("SetTextI18n")
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
            binding.textRemarkLength.text = "$textLength/1000"

        }
    }

    /**
     * 获取意见反馈类型
     */
    private fun loadFeedbackQuestionTypeListAction() {
        typeList.clear()
        for (i in 0..<typeTitleList.size){
            val obj = JSONObject()
            obj.put("title", typeTitleList[i])
            obj.put("value", typeValueList[i])
            obj.put("isSelect",false)
            typeList.add(obj)
        }
        showGombeCreditFeedbackQuestionTypeList()
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        for (i in 0..< typeList.size){
            val obj = typeList[i]
            if (obj.optBoolean("isSelect")){
                selectItem = obj
                break
            }
        }
        return selectItem
    }

    /**
     * 获取上传的图片链接
     */
    private fun getSelectImageUrls(): String{
        var imgUrls = ""
        pictureAdapter?.let {
            for (i in 0..< it.itemCount){
                val item = it.getItem(i)
                if (item.optBoolean("isDefault")){
                    continue
                }
                imgUrls = imgUrls + item.optString("imgUrl") + ","
            }
        }
        if (imgUrls.isNotEmpty()){
            imgUrls = imgUrls.substring(0,imgUrls.length - 1)
        }
        return imgUrls
    }

    /**
     * 获取评分数量
     */
    private fun getStarCount(): String {
        if (intent.extras == null){
            return ""
        }
        return if (intent.extras?.getString(INTENT_KEY_STAR_COUNT) == null) "" else intent.extras?.getString(
            INTENT_KEY_STAR_COUNT
        ).toString()
    }

    /**
     * 设置意见反馈问题类型列表
     */
    private fun showGombeCreditFeedbackQuestionTypeList() {
        binding.userAdviseFlexbox.removeAllViews()
        for (i in 0..< typeList.size) {
            val item = typeList[i]
            val itemBinding = ActGombeCreditUserFeedbackQuestionTypeItemBinding.inflate(layoutInflater)
            itemBinding.textType.text = getString(item.optInt("title"))
            if (item.optBoolean("isSelect")){
                itemBinding.textType.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                itemBinding.imageSelector.setImageResource(R.mipmap.gombe_credit_image_gender_selected_icon)
                itemBinding.itemLayout.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.gombe_credit_fffff5b5))
                    .setStrokeColor(getColor(R.color.theme))
                    .intoBackground()
            } else {
                itemBinding.textType.setTextColor(getColor(R.color.gombe_credit_ffc8c8c8))
                itemBinding.imageSelector.setImageResource(R.mipmap.gombe_credit_image_gender_normal_icon)
                itemBinding.itemLayout.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.gombe_credit_FFF9F9F7))
                    .setStrokeColor(getColor(R.color.gombe_credit_FFF9F9F7))
                    .intoBackground()
            }
            binding.userAdviseFlexbox.addView(itemBinding.root)
            itemBinding.itemLayout.setOnClickListener {
                if (item.optBoolean("isSelect")){
                    return@setOnClickListener
                }
                for (index in 0..< typeList.size){
                    val obj = typeList[index]
                    if (index == i){
                        obj.put("isSelect",true)
                        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_FEEDBACK_QUESTION_TYPE,getString(obj.optInt("title")))
                    } else {
                        obj.put("isSelect",false)
                    }
                }
                showGombeCreditFeedbackQuestionTypeList()
            }
        }
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    fun showGombeCreditUploadImageSuccess(imgPath: String, imgUrl: String) {
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        val lastItem = pictureAdapter?.lastItem as JSONObject
        lastItem.put("imgUrl",imgUrl)

        destinationDirectory?.let {
            if (it.isFile){
                it.delete()
            }
        }
    }

    /**
     * 显示反馈提交成功
     */
    fun showGombeCreditUserFeedbackSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 图片上传
     */
    private fun uploadGombeCreditImageFileAction(imgPath: String){
        showGombeCreditLoading(isTOuchOut = false, isCancel = false)
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    val imgUrl = it.optString("url")
                    showGombeCreditUploadImageSuccess(imgPath,imgUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 提交反馈
     */
    private fun submitFeedbackAction(params: JSONObject){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val msg = data.optString("msg")
                showGombeCreditToast(msg)
                showGombeCreditUserFeedbackSubmitSuccess()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_FEEDBACK_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_FEEDBACK_END)
    }
}